import {
  Shader,
  ShaderData,
  ShaderProperty,
  ShaderPool,
  ShaderProgram,
  ShaderProgramPool,
  ShaderMacro,
  ShaderMacroCollection,
  ShaderDataGroup,
  ShaderLib
} from "@nirvana/shaders";
import { Color } from "@nirvana/math";

import { WebGLCanvas } from "@nirvana/canvas";
import { VertexBufferData, IndexBufferData, DataElement } from "@nirvana/core";

const shaderMacroCollection: ShaderMacroCollection = new ShaderMacroCollection();
console.log(shaderMacroCollection);
const colorShaderData: ShaderData = new ShaderData(ShaderDataGroup.Material);
console.log(ShaderDataGroup, colorShaderData);
const pool: ShaderProgramPool = new ShaderProgramPool();

// 使用使用 Canvas
let canvas = document.getElementById("engine-nirvana");
const webCanvas = new WebGLCanvas(canvas, {});
const engine = webCanvas.engine;
const gl = engine.gl;

const cVS = `
attribute vec3 position;
attribute vec3 color;
varying vec3 vColor;
void main(void) { 
  gl_Position = vec4(position, 1.);
  vColor = color;
}
`;
const cFS = `
varying vec3 vColor;
void main(void) {
  gl_FragColor = vec4(vColor, 1.);
}`;
const colorDemo = Shader.create("colorDemo", cVS, cFS);
console.log(colorDemo, Shader.find("colorDemo"));

const colorProgram: ShaderProgram = colorDemo.getShaderProgram(engine.gl, shaderMacroCollection, pool);
console.log("color", colorProgram);

const vBuffer = new VertexBufferData(
  new Float32Array([
    //前
    0.5, 0.5, 0.5, 0.0, 0.8, 0.0,
    -0.5, 0.5, 0.5, 0.0, 0.8, 0.0,
    -0.5, -0.5, 0.5, 0.0, 0.8, 0.0,
    0.5, -0.5, 0.5, 0.0, 0.8, 0.0,
    //后
    0.5, 0.5, -0.5, 0.6, 0.9, 0.0,
    -0.5, 0.5, -0.5, 0.6, 0.9, 0.0,
    -0.5, -0.5, -0.5, 0.6, 0.9, 0.0,
    0.5, -0.5, -0.5, 0.6, 0.9, 0.0,
    //上
    0.5, 0.5, -0.5, 0.5, 0.5, 0.0,
    -0.5, 0.5, -0.5, 0.5, 0.5, 0.0,
    -0.5, 0.5, 0.5, 0.5, 0.5, 0.0,
    0.5, 0.5, 0.5, 0.5, 0.5, 0.0,
    //下
    0.5, -0.5, -0.5, 0.5, 0.5, 0.0,
    -0.5, -0.5, -0.5, 0.5, 0.5, 0.0,
    -0.5, -0.5, 0.5, 0.5, 0.5, 0.0,
    0.5, -0.5, 0.5, 0.5, 0.5, 0.0,
    //右
    0.5, 0.5, -0.5, 0.9, 0.0, 0.2,
    0.5, 0.5, 0.5, 0.9, 0.0, 0.2,
    0.5, -0.5, 0.5, 0.9, 0.0, 0.2,
    0.5, -0.5, -0.5, 0.9, 0.0, 0.2,
    //左
    -0.5, 0.5, -0.5, 0.6, 0.0, 0.6,
    -0.5, 0.5, 0.5, 0.6, 0.0, 0.6,
    -0.5, -0.5, 0.5, 0.6, 0.0, 0.6,
    -0.5, -0.5, -0.5, 0.6, 0.0, 0.6
  ]),
  [new DataElement("position", 3, gl.FLOAT, false, 24, 0), new DataElement("color", 3, gl.FLOAT, false, 24, 12)]
);

const iBuffer = new IndexBufferData(
  new Uint16Array([
    0, 1, 2, 0, 2, 3,
    4, 6, 5, 4, 7, 6,
    8, 9, 10, 8, 10, 11,
    12, 14, 13, 12, 15, 14,
    16, 17, 18, 16, 18, 19,
    20, 22, 21, 20, 23, 22
  ])
);
vBuffer.create(gl);
iBuffer.create(gl);

engine.update = (gl) => {
  // console.log('--');
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // 用上面指定的颜色清除缓冲区
  gl.clear(gl.COLOR_BUFFER_BIT);

  // 颜色 start 三
  colorProgram.bind();
  vBuffer.upload(colorProgram._glProgram, gl);
  iBuffer.upload(gl);
  iBuffer.draw(gl);
};
